package com.imau.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.imau.bean.*;
import com.imau.mapper.PermissionMapper;
import com.imau.mapper.RoleMapper;
import com.imau.mapper.RolePermissionMapper;
import com.imau.mapper.UserRoleMapper;
import com.imau.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private RolePermissionMapper rolePermissionMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Override
    public int save(Role role) {

        //1.先保存角色基本信息

        int insert = roleMapper.insert(role);

        //2.维护角色权限中间表
        int rows = this.assignPermission(role.getId(), role.getPermissions());


        return insert + rows;
    }


    @Override
    public int deleteById(String id) {

        // 校验 角色是否已经分配用户
        Map<String,Object> columnMap = new HashMap<>();
        columnMap.put("role_id",id);
        List<UserRole> userRoles = userRoleMapper.selectByMap(columnMap);

        if(CollectionUtil.isNotEmpty(userRoles) )
        {
            return  0;
        }

        //1.删除角色表
        int i = roleMapper.deleteById(id);

        int i1 = unAssignPermission(id);
        return i+i1;
    }

    @Override
    public Role findById(String id) {

        //1查询基本信息
        Role role = roleMapper.selectById(id);
        //2查询封装权限信息
        //2.1 查询中间表权限
        List<String> perIds = rolePermissionMapper.selectPerIdsByRoleId(id);
        //2.2 权限id ，查询权限对象
        for(String perId : perIds)
        {
            Permission permission = permissionMapper.selectById(perId);
            role.getPermissions().add(permission);
        }

        return role;
    }

    @Override
    public IPage<Role> queryListByPagte(Role role, int currentPage, int size) {

        LambdaQueryWrapper<Role> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.isNotEmpty(role.getName()),Role::getName,role.getName());
        wrapper.eq(StringUtils.isNotEmpty(role.getStatus()),Role::getStatus,role.getStatus());
        wrapper.between(StringUtils.checkValNotNull(role.getParams().get("biginTime")) && StringUtils.checkValNotNull(role.getParams().get("endTime")),
                Role::getCreateTime,role.getParams().get("biginTime"),role.getParams().get("endTime"));

        IPage<Role> page = new Page<>(1,4);
        return roleMapper.selectPage(page, wrapper);
    }

    @Override
    public int updateRole(Role role) {

        int i = roleMapper.updateById(role);
        if(i>0)
        {
            return this.assignPermission(role.getId(),role.getPermissions());
        }
        return 0;
    }

    @Override
    public int assignPermission(String rid, Set<Permission> permissions) {

        int i= unAssignPermission(rid);

        //2.重新插入角色对应的权限
        if(CollectionUtil.isNotEmpty(permissions))
        {

            for(Permission permission:permissions)
            {
               i = + rolePermissionMapper.insert(new RolePermission(rid,permission.getId()));
            }

        }


        return i;
    }

      @Override
    public int assignPermission(String rid, String[] perids) {

        int i= unAssignPermission(rid);

        //2.重新插入角色对应的权限


            for(String pid :perids)
            {
               i = + rolePermissionMapper.insert(new RolePermission(rid,pid));
            }




        return i;
    }

    @Override
    public int unAssignPermission(String rid) {
        //1.删除中间数据，按照角色id
        Map<String, Object> columnMap = new HashMap<>();
        columnMap.put("role_id",rid);
        int i = rolePermissionMapper.deleteByMap(columnMap);

        return i;
    }
}
